package com.example.administrator.yanfoxconn.activity;

import android.content.Intent;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.Spinner;
import android.widget.TableRow;
import android.widget.TextView;

import com.bumptech.glide.Glide;
import com.example.administrator.yanfoxconn.R;
import com.example.administrator.yanfoxconn.adapter.EmpListAdapter;
import com.example.administrator.yanfoxconn.bean.EmpMessage;
import com.example.administrator.yanfoxconn.bean.KHInfo;
import com.example.administrator.yanfoxconn.bean.KNZWGreen;
import com.example.administrator.yanfoxconn.bean.SelectModel;
import com.example.administrator.yanfoxconn.constant.Constants;
import com.example.administrator.yanfoxconn.constant.FoxContext;
import com.example.administrator.yanfoxconn.constant.ImageCaptureManager;
import com.example.administrator.yanfoxconn.intent.PhotoPickerIntent;
import com.example.administrator.yanfoxconn.utils.BaseActivity;
import com.example.administrator.yanfoxconn.utils.ChangeTextUtils;
import com.example.administrator.yanfoxconn.utils.FileUtil;
import com.example.administrator.yanfoxconn.utils.HttpConnectionUtil;
import com.example.administrator.yanfoxconn.utils.HttpUtils;
import com.example.administrator.yanfoxconn.utils.ImageZipUtils;
import com.example.administrator.yanfoxconn.utils.StringUtils;
import com.example.administrator.yanfoxconn.utils.ToastUtils;
import com.example.administrator.yanfoxconn.widget.MyListView;
import com.google.gson.Gson;
import com.google.gson.JsonArray;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;

import org.json.JSONArray;

import java.io.File;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import androidx.core.content.ContextCompat;
import butterknife.BindView;
import butterknife.ButterKnife;

/**
 * 用途：總務—綠化管理 添加異常界面
 * Created by Song on 2021/9/14.
 */
public class KNAddExceActivity extends BaseActivity implements View.OnClickListener{

    private final int MESSAGE_SET_EXCE = 111;//異常
    private final int MESSAGE_SET_COURSE = 222;//科目
    private final int MESSAGE_SET_SEED = 333;//苗木

    @BindView(R.id.tv_title)
    TextView tvTitle;//標題
    @BindView(R.id.btn_title_left)
    Button btnBack;//返回
    @BindView(R.id.btn_title_right)
    Button btnAdd;//提交

    @BindView(R.id.sp_exce)
    Spinner spExce;//異常情況
    @BindView(R.id.sp_course)
    Spinner spCourse;//歸屬科目
    @BindView(R.id.et_seed)
    EditText etSeed;//苗木名稱
    @BindView(R.id.tr_seed)
    TableRow trSeed;
    @BindView(R.id.lv_seed)
    MyListView lvSeed;//苗木名稱列表
    @BindView(R.id.et_num)
    EditText etNum;//數量
    @BindView(R.id.et_unit)
    EditText etUnit;//單位

    @BindView(R.id.iv_empty1)
    ImageView ivEmptyOne;//空白图片占位
    @BindView(R.id.gv_photo1)
    GridView gridViewOne;//图片显示区域
    private static final int REQUEST_CAMERA_CODE_ONE = 111;
    private static final int REQUEST_PREVIEW_CODE_ONE = 221;
    private ArrayList<String> imagePathsOne = null;//圖片未壓縮地址
    private ArrayList<String> imgZipPathsOne = new ArrayList<String>();//圖片壓縮后地址
    private ImageCaptureManager captureManager; // 相机拍照处理类
    private GridAdapter gridAdapterOne;

    private Map<String,KNZWGreen> listMap;
    private List<KNZWGreen> exceInfo,courseInfo,seedInfo;//異常，科目，苗木
    private String exce,course,seed;
    private List<String> exces,courses,seeds=new ArrayList<>();;
    private int num=0;
    private String isAdd;

    private KNAddExceActivity mContext = this;
    private EmpListAdapter mAdapter;
    private String gId="";
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_kn_add_exce);
        ButterKnife.bind(this);
        btnBack.setOnClickListener(this);
        tvTitle.setText("異動模式");
        btnAdd.setText("提交");
        btnAdd.setVisibility(View.VISIBLE);
        btnAdd.setOnClickListener(this);
        btnBack.setOnClickListener(this);
        ivEmptyOne.setOnClickListener(this);

        gId=getIntent().getStringExtra("result");
        getExce(gId);
        etSeed.setText("");
        //搜索关键字
        etSeed.addTextChangedListener(new TextWatcher() {

            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }
            @Override
            public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {
                if (etSeed.getText().toString().equals("")){}else {
                    seed="";
                    trSeed.setVisibility(View.VISIBLE);
                    String a = etSeed.getText().toString().toUpperCase();
                    //调用适配器里面的搜索方法
                    mAdapter.SearchCity(a);
                }
            }
            @Override
            public void afterTextChanged(Editable editable) {
            }

        });
    }

    @Override
    public void onClick(View view) {
        switch (view.getId()){
            case R.id.btn_title_left://返回
                finish();
                break;
            case R.id.btn_title_right://提交
                check();
                break;
            case R.id.iv_empty1:
            PhotoPickerIntent intent = new PhotoPickerIntent(mContext);
            intent.setSelectModel(SelectModel.MULTI);
            intent.setShowCarema(true); // 是否显示拍照
            intent.setMaxTotal(9); // 最多选择照片数量，默认为3
            intent.setSelectedPaths(imagePathsOne); // 已选中的照片地址， 用于回显选中状态

            startActivityForResult(intent, REQUEST_CAMERA_CODE_ONE);
            break;


        }
    }
    //基本信息下拉   傳值：flag type
    private void getExce(String gId){
        new Thread() {
            @Override
            public void run() {
                String url2 = Constants.HTTP_GREEN_EXCE_INFO+ "?gId=" + gId;

                Log.e("---------", "url2==fff===" + url2);
                //把网络访问的代码放在这里
                String result = HttpUtils.queryStringForPost(url2);
                dismissDialog();
                Gson gson = new Gson();
                if (result != null) {
                    Log.e("---------", "result==fff===" + result);
                    JsonObject jsonObject = new JsonParser().parse(result).getAsJsonObject();
                    String errCode = jsonObject.get("errCode").getAsString();
                    if (errCode.equals("200")) {
                        JsonArray array = jsonObject.get("data").getAsJsonArray();
                        exceInfo = new ArrayList<KNZWGreen>();

                        for (JsonElement type : array) {
                            KNZWGreen humi = gson.fromJson(type, KNZWGreen.class);
                            exceInfo.add(humi);
                        }
                        Message message = new Message();
                        message.what = MESSAGE_SET_EXCE;
                        message.obj = jsonObject.get("errMessage").getAsString();
                        mHandler.sendMessage(message);
                    }
                } else {
                    Message message = new Message();
                    message.what = Constants.MESSAGE_NETMISTAKE;
                    mHandler.sendMessage(message);
                    finish();
                }
            }
        }.start();
    }
    private void setExce(){
        List<String> exceName=new ArrayList<>();
        for (int i = 0;i<exceInfo.size();i++){
            exceName.add(exceInfo.get(i).getBase_id());
        }
        //下拉列表選擇
        spExce.setAdapter(new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, exceName));
        spExce.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
                exce=exceName.get(position);
                if (exceName.get(position).equals("種植")){
                    isAdd="Y";
                    getCourse("");
                }else{
                    isAdd="N";
                    getCourse(gId);
                }

            }
            @Override
            public void onNothingSelected(AdapterView<?> parent) {
            }
        });
    }

    //基本信息下拉：死亡和移植傳區域，種植為空
    private void getCourse(String gId){
        new Thread() {
            @Override
            public void run() {
                String url2 = Constants.HTTP_GREEN_SEED+"?gId="+gId;

                Log.e("---------", "url2==fff===" + url2);
                //把网络访问的代码放在这里
                String result = HttpUtils.queryStringForPost(url2);
                dismissDialog();
                Gson gson = new Gson();
                if (result != null) {
                    Log.e("---------", "result==fff===" + result);
                    JsonObject jsonObject = new JsonParser().parse(result).getAsJsonObject();
                    String errCode = jsonObject.get("errCode").getAsString();
                    if (errCode.equals("200")) {
                        JsonArray array = jsonObject.get("data").getAsJsonArray();
//                        if (gId.equals("")){
                            courseInfo = new ArrayList<KNZWGreen>();

                            for (JsonElement type : array) {
                                KNZWGreen humi = gson.fromJson(type, KNZWGreen.class);
                                courseInfo.add(humi);
                            }
                            Message message = new Message();
                            message.what = MESSAGE_SET_COURSE;
                            message.obj = jsonObject.get("errMessage").getAsString();
                            mHandler.sendMessage(message);
//                        }else{
//                            seedInfo = new ArrayList<KNZWGreen>();
//
//                            for (JsonElement type : array) {
//                                KNZWGreen humi = gson.fromJson(type, KNZWGreen.class);
//                                seedInfo.add(humi);
//                            }
//                            Message message = new Message();
//                            message.what = MESSAGE_SET_SEED;
//                            message.obj = jsonObject.get("errMessage").getAsString();
//                            mHandler.sendMessage(message);
                    }

//                    }
                } else {
                    Message message = new Message();
                    message.what = Constants.MESSAGE_NETMISTAKE;
                    mHandler.sendMessage(message);
                    finish();
                }
            }
        }.start();
    }
    private void setCourse(){
//        List<String> courseName=new ArrayList<>();
//        for (int i = 0;i<courseInfo.size();i++){
//            courseName.add(courseInfo.get(i).getsCourse());
//        }
        //下拉列表選擇
        spCourse.setAdapter(new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, courses));
        spCourse.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
                course=courses.get(position);
                etSeed.setText("");
                seeds.clear();
                trSeed.setVisibility(View.GONE);
                if (listMap != null && listMap.size() != 0) {
                    // 键和值
                    String key = null;
                    KNZWGreen value = null;
                    // 获取键值对的迭代器
                    Iterator it = listMap.entrySet().iterator();
                    while (it.hasNext()) {
                        Map.Entry entry = (Map.Entry) it.next();
                        value = (KNZWGreen) entry.getValue();
                        key = (String) entry.getKey();
                        if (key.split(",")[0].equals(course)){
                            Log.e("---------","value.getGsName()");
                            if (isAdd.equals("Y")){

                                seeds.add(ChangeTextUtils.traToSim(value.getsName())+"-"+value.getUnit());
                            }else{
                                seeds.add(ChangeTextUtils.traToSim(value.getGsName())+"-"+value.getGsNum()+"-"+value.getGsUnit());
                            }
                        }
                    }
                    setSeed();
                }
            }
            @Override
            public void onNothingSelected(AdapterView<?> parent) {
            }
        });
    }
    private void setSeed(){

        mAdapter = new EmpListAdapter(mContext,seeds,"kn");
        lvSeed.setAdapter(mAdapter);

        //稽核門崗列表,選中后1:tit賦值,2:列表隱藏
        mAdapter.OnClickSetText(new EmpListAdapter.OnClickSetText() {
            @Override
            public void OnClickxt(String tit) {
                etSeed.setText(tit);
                seed=tit.split("-")[0];
                if (isAdd.equals("Y")){
                    etUnit.setText(tit.split("-")[1]);
                    num = -1;
                }else{
                    etUnit.setText(tit.split("-")[2]);
                    num = Integer.parseInt(tit.split("-")[1]);}
//                paramMap.put("mengang", empFileList.get(position).getID());
                mAdapter.SearchCity("");
                trSeed.setVisibility(View.GONE);
            }

            @Override
            public void OnClicktv(String tit, String tv) {

            }
        });
    }
    //提交前檢查
    private void check(){
        if(FoxContext.getInstance().getLoginId().equals("")){
            ToastUtils.showLong(mContext,"登錄超時,請退出重新登錄!");
            return;
        }
        if (etNum.getText().toString().equals("")){
            ToastUtils.showShort(mContext,"請輸入正確數量！");
            return;
        }else if (num==-1){

        }else if (Integer.parseInt(etNum.getText().toString())>num){

            ToastUtils.showShort(mContext,"請輸入正確數量！");
            return;
        }
        if (etSeed.getText().toString().equals("")||seed.equals("")){
            ToastUtils.showShort(mContext,"請選擇具体苗木！");
            return;
        }
        if (imagePathsOne==null) {
            ToastUtils.showShort(this, "請上傳照片");
            return;
        }
        upMsessage();
    }
    //提交信息
    private void upMsessage() {

        final String url = Constants.HTTP_GREEN_EXCE_POST; //此處寫上自己的URL

        JsonObject object = new JsonObject();

        JsonArray photoArray1 = new JsonArray();

        if (imagePathsOne != null) {
            for (int i = 0; i < imagePathsOne.size(); i++) {
                File pictureFile = new File(imagePathsOne.get(i)); //通過路徑獲取檔
                final String pic_path = imagePathsOne.get(i);
                String sign_dir = Environment.getExternalStorageDirectory() + File.separator + "YanFoxconn" + File.separator + "Photos";
                String _path =  sign_dir + File.separator  + System.currentTimeMillis() +i+ ".jpg";
                final String compressImage = ImageZipUtils.compressImage(pic_path, _path, 30);
                String picBase64Code = ImageZipUtils.imageToBase64(compressImage);
                JsonObject jsonObject1 = new JsonObject();
                jsonObject1.addProperty("file", picBase64Code);
                photoArray1.add(jsonObject1);
            }
            object.add("photo", photoArray1);
        }

        object.addProperty("gId",gId);
        object.addProperty("gName",getIntent().getStringExtra("gName"));
        object.addProperty("gcName",course);
        object.addProperty("gsName",seed);
        object.addProperty("geNum",etNum.getText().toString());
        object.addProperty("geUnit",etUnit.getText().toString());
        object.addProperty("geResult",exce);
        object.addProperty("geUser", FoxContext.getInstance().getName());

        Log.e("----object----",  object.toString());

        //開啟一個新執行緒，向伺服器上傳資料
        new Thread() {
            public void run() {
                //把网络访问的代码放在这里
                try {
                    showDialog();
                    Log.e("-----url----",  url);
                    String result = HttpConnectionUtil.doPostJsonObject(url, object);
                    if (result != null) {
                        dismissDialog();
                        Log.e("----result-----",  result);
                        JsonObject jsonObject = new JsonParser().parse(result).getAsJsonObject();
                        String errCode = jsonObject.get("errCode").getAsString();
                        if (errCode.equals("200")) {
                            Message message = new Message();
                            message.what = Constants.MESSAGE_TOAST;
                            message.obj = jsonObject.get("errMessage").getAsString();
                            mHandler.sendMessage(message);

                        } else{
                            Message message = new Message();
                            message.what = Constants.MESSAGE_ALERT;
                            message.obj = jsonObject.get("errMessage").getAsString();
                            mHandler.sendMessage(message);
                        }
                    }else{
                        Message message = new Message();
                        message.what = Constants.MESSAGE_NETMISTAKE;
                        mHandler.sendMessage(message);
                        finish();
                    }

                } catch (Exception e) {
                    e.printStackTrace();
                }finally {
                    FileUtil.deletePhotos(mContext);
                }
            }
        }.start();
    }

    Handler mHandler = new Handler() {
        public void handleMessage(Message msg) {
            switch (msg.what) {

                case Constants.MESSAGE_TOAST://Toast彈出
                    ToastUtils.showLong(mContext, msg.obj.toString());
                    finish();
                    break;
                case Constants.MESSAGE_UP://提交響應
//                    worningAlert(msg.obj.toString(),Constants.MESSAGE_TOAST);
//                    ToastUtils.showLong(CrossScanActivity.this, msg.obj.toString());
                    break;
                case Constants.MESSAGE_ALERT://提交響應
                    ToastUtils.showLong(KNAddExceActivity.this, msg.obj.toString());
                   finish();
                    break;
                case MESSAGE_SET_EXCE:
                    setExce();
                    break;
                case MESSAGE_SET_COURSE:
                    listMap = new HashMap<>();
                    courses = new ArrayList<>();
                    for (int i=0;i<courseInfo.size();i++){
                        if (isAdd.equals("Y")){

                            listMap.put(courseInfo.get(i).getsCourse()+","+i,courseInfo.get(i));

                            if (i==0){
                                courses.add(courseInfo.get(i).getsCourse());
                            }else if (!courseInfo.get(i-1).getsCourse().equals(courseInfo.get(i).getsCourse())){
                                courses.add(courseInfo.get(i).getsCourse());}
                        }else{

                            listMap.put(courseInfo.get(i).getGcName()+","+i,courseInfo.get(i));

                            if (i==0){
                                courses.add(courseInfo.get(i).getGcName());
                            }else if (!courseInfo.get(i-1).getGcName().equals(courseInfo.get(i).getGcName())){
                                courses.add(courseInfo.get(i).getGcName());}
                        }
                    }

                    setCourse();

                    break;
                case MESSAGE_SET_SEED:
//                   List<String> seedList = new ArrayList<>();
//                    for (int i = 0;i<seedInfo.size();i++){
//                        seedList.add(seedInfo.get(i).getsName());
//                    }

                    break;
            }
            super.handleMessage(msg);
        }
    };
    //照片上傳 返回
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK) {

            switch (requestCode) {
                // 选择照片
                case REQUEST_CAMERA_CODE_ONE:
                    loadAdpater(data.getStringArrayListExtra(PhotoPickerActivity.EXTRA_RESULT), requestCode);
                    break;
                // 预览
                case REQUEST_PREVIEW_CODE_ONE:
                    loadAdpater(data.getStringArrayListExtra(PhotoPreviewActivity.EXTRA_RESULT), requestCode);
                    break;
                // 调用相机拍照
                case ImageCaptureManager.REQUEST_TAKE_PHOTO:
                    if (captureManager.getCurrentPhotoPath() != null) {
                        captureManager.galleryAddPic();

                        ArrayList<String> paths = new ArrayList<>();
                        paths.add(captureManager.getCurrentPhotoPath());
                        loadAdpater(paths, requestCode);
                        Log.e("==========", paths.get(1));
                    }
                    break;
            }
        }
    }

    private void loadAdpater(ArrayList<String> paths, int code) {
        switch (code) {
            case REQUEST_CAMERA_CODE_ONE:
                loadOne(paths);
                break;
            case REQUEST_PREVIEW_CODE_ONE:
                loadOne(paths);
                break;
        }
    }

    private void loadOne(ArrayList<String> paths) {
        if (imagePathsOne == null) {
            imagePathsOne = new ArrayList<>();
        }
        imagePathsOne.clear();
        imagePathsOne.addAll(paths);

        if (paths.size() > 0) {
            ivEmptyOne.setVisibility(View.GONE);
        } else {
            ivEmptyOne.setVisibility(View.VISIBLE);
        }

        try {
            JSONArray obj = new JSONArray(imagePathsOne);
            Log.e("--", obj.toString());
        } catch (Exception e) {
            e.printStackTrace();
        }

        if (gridAdapterOne == null) {
            gridAdapterOne = new GridAdapter(imagePathsOne);
            gridViewOne.setAdapter(gridAdapterOne);
            Log.e("----------------", "ddd==" + imagePathsOne.size());
        } else {
            gridAdapterOne.notifyDataSetChanged();
        }
    }

    private class GridAdapter extends BaseAdapter {
        private ArrayList<String> listUrls;

        public GridAdapter(ArrayList<String> listUrls) {
            this.listUrls = listUrls;
        }

        @Override
        public int getCount() {
            if (listUrls.size() == 9) {
                return 9;
            } else {
                return listUrls.size() + 1;
            }

        }

        @Override
        public String getItem(int position) {
            return listUrls.get(position);
        }

        @Override
        public long getItemId(int position) {
            return position;
        }

        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            ImageView imageView;
            if (convertView == null) {
                convertView = getLayoutInflater().inflate(R.layout.item_image, null);
                imageView = (ImageView) convertView.findViewById(R.id.imageView);
                convertView.setTag(imageView);
                // 重置ImageView宽高
//                LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(columnWidth, columnWidth);
//                imageView.setLayoutParams(params);
            } else {
                imageView = (ImageView) convertView.getTag();
            }

            if (position == listUrls.size()) {
                imageView.setImageBitmap(BitmapFactory.decodeResource(getResources(), R.mipmap.icon_addpic_unfocused));
                if (position == 9) {
                    imageView.setVisibility(View.GONE);
                }
            } else {
                Glide.with(mContext)
                        .load(new File(getItem(position)))
                        .placeholder(R.mipmap.default_error)
                        .error(R.mipmap.default_error)
                        .centerCrop()
                        .crossFade()
                        .into(imageView);
            }
            return convertView;
        }
    }

}
